import 'package:flutter/material.dart';
import 'package:flutter_architecture_samples_vanilla/localization.dart';
import 'package:todos_app_core/todos_app_core.dart';
import 'package:todos_repository_core/todos_repository_core.dart';
import 'models.dart';
import 'screen/home_screen.dart';
import 'screen/add_edit_screen.dart';

class VanillaApp extends StatefulWidget {
  const VanillaApp({required this.repository});
  final TodosRepository repository;
  @override
  State<VanillaApp> createState() => _VanillaAppState();
}

class _VanillaAppState extends State<VanillaApp> {
  AppState appState = AppState.loading();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.repository.loadTodos().then((loadedTodos) {
      setState(() {
        appState = AppState(todos: loadedTodos.map(Todo.fromEntity).toList());
      });
    }).catchError((err) {
      setState(() {
        appState.isLoading = false;
      });
    });
  }

  void removeTodo(Todo todo) {
    setState(() {
      appState.todos.remove(todo);
    });
  }

  void addTodo(Todo todo) {
    setState(() {
      appState.todos.add(todo);
    });
  }

  void updateTodo(
    Todo todo, {
    bool? complete,
    String? task,
    String? id,
    String? note,
  }) {
    setState(() {
      todo.complete = complete ?? todo.complete;
      todo.id = id ?? todo.id;
      todo.task = task ?? todo.task;
      todo.note = note ?? todo.note;
    });
  }

  void toggleAll() {
    setState(() {
      appState.toggleAll();
    });
  }

  void clearCompleted() {
    setState(() {
      appState.clearCompleted();
    });
  }

  void inverseCompleted() {
    setState(() {
      appState.inverseCompleted();
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      onGenerateTitle: (context) => VanillaLocalizations.of(context)!.appTitle,
      theme: ArchSampleTheme.theme,
      localizationsDelegates: [
        ArchSampleLocalizationsDelegate(),
        VanillaLocalizationsDelegate(),
      ],
      routes: {
        ArchSampleRoutes.home: (context) {
          return HomeScreen(
            updateTodo: updateTodo,
            removeTodo: removeTodo,
            appState: appState,
            addTodo: addTodo,
            toggleAll: toggleAll,
            clearCompleted: clearCompleted,
            inverseCompleted: inverseCompleted,
          );
        },
        ArchSampleRoutes.addTodo: (context) {
          return AddEditScreen(
            addTodo: addTodo,
            updateTodo: updateTodo,
            key: ArchSampleKeys.addTodoScreen,
          );
        }
      },
    );
  }
}
